<template>
  <view class="message-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="navbar-left" @tap.stop="toggleMenu">
          <view class="add-icon" :class="{ active: showMenuPopup }">
            <view class="add-icon-line add-icon-line-h"></view>
            <view class="add-icon-line add-icon-line-v"></view>
          </view>
        </view>
        <view class="navbar-title">消息</view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 遮罩层 -->
    <view v-if="showMenuPopup" class="menu-overlay" @tap="showMenuPopup = false"></view>

    <!-- 气泡菜单 -->
    <view class="bubble-menu" :class="{ show: showMenuPopup }" :style="{ top: bubbleMenuTop }">
      <view class="bubble-menu-item" @tap="handleCreateGroup">
        <view class="bubble-menu-icon">
          <u-icon name="account-fill" size="20" color="#4A90E2"></u-icon>
        </view>
        <text class="bubble-menu-text">发起群聊</text>
      </view>
      <view class="bubble-menu-item" @tap="handleAddFriend">
        <view class="bubble-menu-icon">
          <u-icon name="account" size="20" color="#4A90E2"></u-icon>
        </view>
        <text class="bubble-menu-text">添加朋友</text>
      </view>
      <view class="bubble-menu-item" @tap="handleScan">
        <view class="bubble-menu-icon">
          <u-icon name="scan" size="20" color="#4A90E2"></u-icon>
        </view>
        <text class="bubble-menu-text">扫一扫</text>
      </view>
    </view>

    <!-- 顶部Tab切换 -->
    <view class="tab-bar" :style="{ marginTop: tabBarTop }">
      <view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
        @tap="switchTab(index)">
        <text class="tab-text">{{ tab.name }}</text>
        <view v-if="tab.badge > 0" class="badge">{{ tab.badge > 99 ? '99+' : tab.badge }}</view>
        <view v-if="currentTab === index" class="tab-indicator"></view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view v-if="currentTab === 0" class="message-list" scroll-y>
      <view v-for="(item, index) in messageList" :key="index" class="message-item" @tap="openChat(item)">
        <view class="avatar-wrapper">
          <image class="avatar" :src="item.avatar" mode="aspectFill"></image>
          <view v-if="item.unread > 0" class="unread-badge">{{ item.unread > 99 ? '99+' : item.unread }}</view>
        </view>
        <view class="message-content">
          <view class="content-header">
            <text class="username">{{ item.username }}</text>
            <text class="time">{{ item.time }}</text>
          </view>
          <text class="last-message" :class="{ unread: item.unread > 0 }">{{ item.lastMessage }}</text>
        </view>
      </view>
      <view v-if="messageList.length === 0" class="empty-state">
        <text class="empty-icon">💬</text>
        <text class="empty-text">暂无消息</text>
      </view>
    </scroll-view>

    <!-- 通知列表 -->
    <scroll-view v-if="currentTab === 1" class="notification-list" scroll-y @scrolltolower="loadMoreNotifications">
      <view v-for="(item, index) in notificationList" :key="item.id || index" class="notification-item"
        :class="{ unread: !item.read }" @tap="handleNotificationClick(item)">
        <view class="notification-icon" :style="{ backgroundColor: item.iconBg }">
          <text class="icon-text">{{ item.icon }}</text>
        </view>
        <view class="notification-content">
          <text class="notification-title">{{ item.title }}</text>
          <text class="notification-desc">{{ item.content }}</text>
          <text class="notification-time">{{ item.time }}</text>
        </view>
        <view v-if="!item.read" class="unread-dot"></view>
      </view>
      <view v-if="notificationList.length === 0 && !loadingNotifications" class="empty-state">
        <text class="empty-icon">🔔</text>
        <text class="empty-text">暂无通知</text>
      </view>
      <view v-if="loadingNotifications" class="loading-wrapper">
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>

    <!-- 自定义 TabBar -->
    <custom-tabbar :current="2" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import {
  getConversations,
  getNotifications,
  markNotificationAsRead,
  getUnreadNotificationsCount,
  type ConversationInfo,
  type NotificationInfo,
  NotificationType
} from '@/api/messages'
import { acceptFriendRequest, rejectFriendRequest } from '@/api/friends'

// 状态栏高度
const statusBarHeight = ref(0)

// 菜单弹出状态
const showMenuPopup = ref(false)

// Tab标签
const tabs = ref([
  { name: '消息', badge: 0 },
  { name: '通知', badge: 0 }
])

const currentTab = ref(0)

// 消息列表（会话列表）
const messageList = ref<Array<{
  conversationId: string
  userId: number
  avatar: string
  username: string
  lastMessage: string
  time: string
  unread: number
}>>([])

// 通知列表
const notificationList = ref<Array<{
  id: number
  type: string
  title: string
  content: string
  time: string
  read: boolean
  icon: string
  iconBg: string
  trigger?: { id: number; username?: string; avatar?: string }
  data?: Record<string, any>
}>>([])

// 通知加载状态
const loadingNotifications = ref(false)
const notificationPage = ref(1)
const hasMoreNotifications = ref(true)

// 切换Tab
const switchTab = (index: number) => {
  currentTab.value = index
}

// 加载会话列表
const loadConversations = async () => {
  try {
    const response = await getConversations(1, 50)

    if (response.data && response.data.length > 0) {
      messageList.value = response.data.map((conv: ConversationInfo) => {
        // 格式化时间
        const formatTime = (timeStr?: string): string => {
          if (!timeStr) return ''
          const date = new Date(timeStr)
          const now = new Date()
          const diff = now.getTime() - date.getTime()
          const minutes = Math.floor(diff / 60000)
          const hours = Math.floor(diff / 3600000)
          const days = Math.floor(diff / 86400000)

          if (minutes < 1) return '刚刚'
          if (minutes < 60) return `${minutes}分钟前`
          if (hours < 24) return `${hours}小时前`
          if (days < 7) return `${days}天前`

          const month = date.getMonth() + 1
          const day = date.getDate()
          const hour = date.getHours()
          const minute = date.getMinutes()
          return `${month}/${day} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
        }

        return {
          conversationId: conv.conversationId,
          userId: conv.otherUser.id,
          avatar: conv.otherUser.avatar || '/static/logo.png',
          username: conv.otherUser.username || conv.otherUser.nickname || '用户',
          lastMessage: conv.lastMessageContent || '',
          time: formatTime(conv.lastMessageAt),
          unread: conv.unreadCount
        }
      })

      // 更新Tab徽章
      const totalUnread = messageList.value.reduce((sum, item) => sum + item.unread, 0)
      tabs.value[0].badge = totalUnread > 0 ? totalUnread : 0
    } else {
      messageList.value = []
      tabs.value[0].badge = 0
    }
  } catch (error: any) {
    console.error('加载会话列表失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  }
}

// 打开聊天
const openChat = (item: any) => {
  uni.navigateTo({
    url: `/pages/chat/chat?conversationId=${item.conversationId}&userId=${item.userId}`
  })
}

// 加载通知列表
const loadNotifications = async (isLoadMore: boolean = false) => {
  if (loadingNotifications.value || (!hasMoreNotifications.value && isLoadMore)) return

  loadingNotifications.value = true
  try {
    const currentPage = isLoadMore ? notificationPage.value + 1 : 1
    const response = await getNotifications(currentPage, 20)

    if (response.data && response.data.length > 0) {
      const newNotifications = response.data.map((notif: NotificationInfo) => {
        // 根据通知类型设置图标和背景色
        const getNotificationStyle = (type: NotificationType) => {
          switch (type) {
            case NotificationType.FRIEND_REQUEST:
              return { icon: '👥', iconBg: '#E5F3FF' }
            case NotificationType.FRIEND_ACCEPTED:
              return { icon: '✅', iconBg: '#E5FFE5' }
            case NotificationType.WORK_LIKED:
              return { icon: '❤️', iconBg: '#FFE5E5' }
            case NotificationType.WORK_COLLECTED:
              return { icon: '⭐', iconBg: '#FFF5E5' }
            case NotificationType.WORK_COMMENTED:
            case NotificationType.COMMENT_REPLIED:
              return { icon: '💬', iconBg: '#E5F3FF' }
            case NotificationType.SYSTEM:
              return { icon: '🎉', iconBg: '#F0E5FF' }
            default:
              return { icon: '🔔', iconBg: '#F5F5F5' }
          }
        }

        const style = getNotificationStyle(notif.type)

        // 格式化时间
        const formatTime = (timeStr: string): string => {
          if (!timeStr) return ''
          const date = new Date(timeStr)
          const now = new Date()
          const diff = now.getTime() - date.getTime()
          const minutes = Math.floor(diff / 60000)
          const hours = Math.floor(diff / 3600000)
          const days = Math.floor(diff / 86400000)

          if (minutes < 1) return '刚刚'
          if (minutes < 60) return `${minutes}分钟前`
          if (hours < 24) return `${hours}小时前`
          if (days < 7) return `${days}天前`

          const month = date.getMonth() + 1
          const day = date.getDate()
          const hour = date.getHours()
          const minute = date.getMinutes()
          return `${month}/${day} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
        }

        return {
          id: notif.id,
          type: notif.type,
          title: notif.title,
          content: notif.content,
          time: formatTime(notif.createdAt),
          read: notif.isRead,
          icon: style.icon,
          iconBg: style.iconBg,
          trigger: notif.trigger,
          data: notif.data || undefined
        }
      })

      if (isLoadMore) {
        notificationList.value.push(...newNotifications)
        notificationPage.value = currentPage
      } else {
        notificationList.value = newNotifications
        notificationPage.value = 1
      }

      hasMoreNotifications.value = response.data.length >= 20

      // 更新Tab徽章
      const unreadCount = notificationList.value.filter(n => !n.read).length
      tabs.value[1].badge = unreadCount > 0 ? unreadCount : 0
    } else {
      if (!isLoadMore) {
        notificationList.value = []
      }
      hasMoreNotifications.value = false
      tabs.value[1].badge = 0
    }
  } catch (error: any) {
    console.error('加载通知列表失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loadingNotifications.value = false
  }
}

// 加载更多通知
const loadMoreNotifications = () => {
  if (hasMoreNotifications.value && !loadingNotifications.value) {
    loadNotifications(true)
  }
}

// 处理通知点击
const handleNotificationClick = async (notification: any) => {
  // 标记为已读
  if (!notification.read) {
    try {
      await markNotificationAsRead(notification.id)
      notification.read = true
      tabs.value[1].badge = Math.max(0, tabs.value[1].badge - 1)
    } catch (error: any) {
      console.error('标记通知已读失败:', error)
    }
  }

  // 根据通知类型执行不同操作
  switch (notification.type) {
    case NotificationType.FRIEND_REQUEST:
      // 好友请求：显示接受/拒绝对话框
      handleFriendRequest(notification)
      break
    case NotificationType.WORK_LIKED:
    case NotificationType.WORK_COMMENTED:
    case NotificationType.COMMENT_REPLIED:
      // 点赞/评论：跳转到作品详情页
      if (notification.data?.workId) {
        uni.navigateTo({
          url: `/pages/detail/detail?id=${notification.data.workId}`
        })
      }
      break
    case NotificationType.WORK_COLLECTED:
      // 收藏：可以跳转到作品详情页或用户主页
      if (notification.data?.workId) {
        uni.navigateTo({
          url: `/pages/detail/detail?id=${notification.data.workId}`
        })
      }
      break
    default:
      // 其他通知：只标记为已读
      break
  }
}

// 处理好友请求
const handleFriendRequest = (notification: any) => {
  const friendshipId = notification.data?.friendshipId
  if (!friendshipId) {
    uni.showToast({
      title: '数据错误',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '好友请求',
    content: notification.content,
    confirmText: '接受',
    cancelText: '拒绝',
    success: async (res) => {
      try {
        if (res.confirm) {
          // 接受好友请求
          await acceptFriendRequest(friendshipId)
          uni.showToast({
            title: '已接受',
            icon: 'success'
          })
        } else {
          // 拒绝好友请求
          await rejectFriendRequest(friendshipId)
          uni.showToast({
            title: '已拒绝',
            icon: 'none'
          })
        }
        // 刷新通知列表
        await loadNotifications()
      } catch (error: any) {
        console.error('处理好友请求失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    }
  })
}

// 标记为已读（兼容旧代码）
const markAsRead = (index: number) => {
  handleNotificationClick(notificationList.value[index])
}

// 获取状态栏高度
onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
  // 加载会话列表
  loadConversations()
  // 加载通知列表
  loadNotifications()
})

// 页面显示时刷新数据
onShow(() => {
  loadConversations()
  loadNotifications()
})

// 计算气泡菜单位置（px转rpx，1px ≈ 2rpx）
const bubbleMenuTop = computed(() => {
  return (statusBarHeight.value * 2 + 88) + 'rpx'
})

// 计算Tab栏位置（导航栏高度 + 状态栏高度）
const tabBarTop = computed(() => {
  return (statusBarHeight.value * 2 + 88) + 'rpx'
})

// 切换菜单显示
const toggleMenu = () => {
  showMenuPopup.value = !showMenuPopup.value
}

// 扫一扫
const handleScan = () => {
  showMenuPopup.value = false
  uni.scanCode({
    success: (res) => {
      console.log('扫码结果:', res)
      uni.showToast({
        title: '扫码成功',
        icon: 'success'
      })
      // TODO: 处理扫码结果
    },
    fail: (err) => {
      console.error('扫码失败:', err)
      uni.showToast({
        title: '扫码失败',
        icon: 'none'
      })
    }
  })
}

// 添加好友
const handleAddFriend = () => {
  showMenuPopup.value = false
  uni.navigateTo({
    url: '/pages/addFriend/addFriend'
  })
}

// 发起群聊
const handleCreateGroup = () => {
  showMenuPopup.value = false
  uni.showToast({
    title: '发起群聊',
    icon: 'none'
  })
  // TODO: 跳转到创建群聊页面
  // uni.navigateTo({
  //   url: '/pages/create-group/create-group'
  // })
}
</script>

<style scoped>
.message-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 100rpx;
}

/* 自定义导航栏 */
.custom-navbar {
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  border-bottom: 1rpx solid #f0f0f0;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.navbar-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 1001;
}

/* 加号图标 */
.add-icon {
  width: 48rpx;
  height: 48rpx;
  position: relative;
  transition: transform 0.3s ease;
}

.add-icon.active {
  transform: rotate(45deg);
}

.add-icon-line {
  position: absolute;
  background-color: #333;
  transition: background-color 0.3s ease;
}

.add-icon-line-h {
  width: 24rpx;
  height: 2rpx;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.add-icon-line-v {
  width: 2rpx;
  height: 24rpx;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.add-icon.active .add-icon-line {
  background-color: #4A90E2;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.navbar-right {
  width: 60rpx;
}

/* 遮罩层 */
.menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 2000;
  animation: fadeIn 0.2s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

/* 气泡菜单 */
.bubble-menu {
  position: fixed;
  left: 30rpx;
  z-index: 2001;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  padding: 20rpx 0;
  min-width: 280rpx;
  opacity: 0;
  transform: scale(0.9) translateY(-10rpx);
  transform-origin: top left;
  pointer-events: none;
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.bubble-menu.show {
  opacity: 1;
  transform: scale(1) translateY(0);
  pointer-events: auto;
}

.bubble-menu-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  gap: 20rpx;
  transition: background-color 0.2s ease;
}

.bubble-menu-item:active {
  background-color: #f5f5f5;
}

.bubble-menu-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bubble-menu-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

/* Tab栏 */
.tab-bar {
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
  flex: 1;
  padding: 30rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #4A90E2;
  font-weight: bold;
  font-size: 32rpx;
}

.badge {
  position: absolute;
  top: 20rpx;
  right: 25%;
  background-color: #ff4444;
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}

.tab-indicator {
  width: 60rpx;
  height: 6rpx;
  background-color: #4A90E2;
  border-radius: 3rpx;
  margin-top: 10rpx;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
}

.message-item {
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.avatar-wrapper {
  position: relative;
  margin-right: 20rpx;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.unread-badge {
  position: absolute;
  top: -5rpx;
  right: -5rpx;
  background-color: #ff4444;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}

.message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.username {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.time {
  font-size: 22rpx;
  color: #999;
}

.last-message {
  font-size: 26rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.last-message.unread {
  color: #333;
  font-weight: 500;
}

/* 通知列表 */
.notification-list {
  flex: 1;
  overflow-y: auto;
}

.notification-item {
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.notification-item.unread {
  background-color: #f8f9fa;
}

.notification-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.icon-text {
  font-size: 40rpx;
}

.notification-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.notification-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.notification-desc {
  font-size: 26rpx;
  color: #666;
}

.notification-time {
  font-size: 22rpx;
  color: #999;
}

.unread-dot {
  width: 16rpx;
  height: 16rpx;
  background-color: #ff4444;
  border-radius: 50%;
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  gap: 20rpx;
}

.empty-icon {
  font-size: 100rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}
</style>
